package mess;

import java.util.ArrayList;
import java.util.List;

public class LeeCode_54 {
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
        int[][] matrix2 = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(spiralOrder(matrix2));
    }
    private static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int m = matrix.length;
        int n = matrix[0].length;
        int remain = m;
        while (remain > 0){
            int start = (m - remain) / 2;
            for (int j = start; j < n - start; j++) {
                res.add(matrix[start][j]);
            }
            if (res.size() == m * n)
                break;
            for (int i = start + 1; i < m - start; i++) {
                res.add(matrix[i][n - start - 1]);
            }
            if (res.size() == m * n)
                break;
            for (int j = n - start - 2; j >= start; j--) {
                res.add(matrix[m - start - 1][j]);
            }
            for (int i = m - start - 2; i > start; i--) {
                res.add(matrix[i][start]);
            }
            remain -= 2;
        }
        return res;
    }
}
